<?php

namespace app\health\controller;

use app\common\library\time\TimeHelper;
use app\health\model\HealthFuluActivity;
use app\health\model\HealthFuluGoods;
use app\health\model\HealthFuluOrder;
use app\health\model\HealthFuluOrderItem;
use app\health\model\HealthPayment;
use app\health\service\EquityCenterService;
use app\health\service\WePayService;
use RedisException;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\DbException;

class Fulu extends ApiBase
{
    /**
     * 权益商品列表
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function lists(): void
    {
        $lists = HealthFuluGoods::where('status', 1)
            ->where('type', 0)
            ->where('deleted', 0)
            ->order('sort', 'desc')
            ->select();
        $data  = [];
        $isVip = EquityCenterService::isPajkVip($this->auth->mobile);
        foreach ($lists as $list) {
            $price           = $isVip ? $list['vip_price'] : $list['price'];
            $discount        = bcsub($list['price'], $price, 2);
            $data['goods'][] = [
                'id'             => $list['id'],
                'name'           => $list['name'],
                'icon'           => $list['icon'],
                'price'          => $isVip ? $list['vip_price'] : $list['price'],
                'original_price' => $list['price'],
                'discount'       => $discount,
                'must_element'   => $list['must_element']
            ];
        }
        $data['user']  = [
            'is_vip' => $isVip,
            'mobile' => $this->auth->mobile
        ];
        $data['rule']  = [
            '购买前请仔细核对充值账号',
            '买错商品活充错账号，均无法退款，请特别注意',
            '到账时间：1-10分钟',
            '虚拟商品均不支持退款',
        ];
        $data['bonus'] = ['image' => 'https://xinhuzhu.xinquanyu.top/uploads/20230818/b2e7afeee2df500fca8ed1c953220cf0.jpg'];
        $this->success('success', $data);
    }

    /**
     * 下单预校验
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function precheck(): void
    {
        $params = $this->request->param();
        $data   = $this->extracted($params['goods_id'] ?? []);
        $this->success('success', $data);
    }

    /**
     * 创建订单
     * @return void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function create_order(): void
    {
        $params = $this->request->param();
        if (empty($params['goods']) || count($params['goods']) === 0) {
            $this->error('请选择购买的商品');
        }
        $goodsItem = [];
        $goodsIds  = [];
        foreach ($params['goods'] as $good) {
            $goodsIds[]                   = $good['goods_id'];
            $goodsItem[$good['goods_id']] = $good['account'];
        }
        $data      = $this->extracted($goodsIds);
        $orderItem = [];
        foreach ($data['items'] as &$item) {
            if (empty($goodsItem[$item['id']])) {
                $this->error('请输入' . $item['name'] . '的账号');
            }
            $orderItem[] = [
                'goods_id'       => $item['id'],
                'goods_name'     => $item['name'],
                'goods_code'     => $item['goods_code'],
                'account'        => $goodsItem[$item['id']],
                'price'          => $item['price'],
                'discount_price' => $item['discount_price'],
                'original_price' => $item['original_price'],
                'cost_price'     => $item['cost_price'],
            ];
        }
        //创建订单
        try {
            Db::startTrans();
            $order = HealthFuluOrder::create([
                'type'           => 0,
                'order_no'       => create_trade_no('F'),
                'user_id'        => $this->auth->id,
                'total_price'    => $data['total_price'],
                'pay_price'      => $data['total_price'],
                'discount_price' => $data['discount_price'],
            ]);
            $order->orderItem()->saveAll($orderItem);
            //创建支付订单
            $payment    = HealthPayment::create([
                'type'            => 2,
                'user_id'         => $this->auth->id,
                'order_no'        => $order['order_no'],
                'pay_description' => '会员月卡购买',
                'pay_way'         => HealthPayment::PAY_WAY_WECHAT,
                'pay_money'       => $order['pay_price'],
                //                'pay_money'       => 0.01,
                'pay_status'      => 0
            ]);
            $pay_config = HealthPayment::createdWechatPay($payment, $this->auth->openid);
            if (empty($pay_config['prepay_id'])) {
                throw new \Exception('微信支付创建失败');
            }
            $pay_config = WePayService::WePayOrder()->jsapiParams($pay_config['prepay_id']);
            Db::commit();
        } catch (\Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }
        $this->success('success', [
            'pay_config' => $pay_config,
            'payment_id' => $payment['id'],
            'pay_status' => $payment['pay_status']
        ]);
    }

    /**
     * @param array $goodsId
     * @return array
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     * @throws DbException
     */
    private function extracted(array $goodsId = []): array
    {
        $params     = $this->request->param();
        $goodsLists = HealthFuluGoods::whereIn('id', $goodsId)
            ->where('status', 1)
            ->where('type', 0)
            ->select();
        $data       = ['total_price' => 0.00, 'discount_price' => 0.00, 'items' => []];
        $isVip      = EquityCenterService::isPajkVip($this->auth->mobile);
        foreach ($goodsLists as $list) {
            $price                  = $isVip ? $list['vip_price'] : $list['price'];
            $discount               = bcsub($list['price'], $price, 2);
            $data['total_price']    = bcadd($data['total_price'], $price, 2);
            $data['discount_price'] = bcadd($data['discount_price'], $discount, 2);
            $data['items'][]        = [
                'id'             => $list['id'],
                'name'           => $list['name'],
                'goods_code'     => $list['goods_code'],
                'price'          => $price,
                'original_price' => $list['price'],
                'discount_price' => $discount,
                'cost_price'     => $list['cost_price'],
                'must_element'   => $list['must_element']
            ];
        }
        return $data;
    }


    /**
     * 用户权益列表
     * @return void
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function record_item(): void
    {
        $activity = HealthFuluActivity::where('mobile', $this->auth->mobile)->cache(true, TimeHelper::secondEndToday())->find();
        if ($activity && $activity['active_state'] === 0) {
            //创建订单
            $activity->save(['is_register' => 1, 'active_state' => 1]);
            $order     = HealthFuluOrder::create([
                'type'       => 3,
                'order_no'   => empty($activity['order_no']) ? create_trade_no('F') : $activity['order_no'],
                'user_id'    => $this->auth->id,
                'pay_time'   => time(),
                'pay_status' => 1,
            ]);
            $fuluGoods = HealthFuluGoods::where('id', $activity['fulu_goods_id'])->find();
            $order->orderItem()->save([
                'goods_id'       => $activity['fulu_goods_id'],
                'goods_name'     => $fuluGoods['name'] ?? '',
                'goods_code'     => $fuluGoods['goods_code'] ?? '',
                'account'        => $activity['account'],
                'price'          => 0,
                'discount_price' => 0,
                'original_price' => 0,
                'cost_price'     => 0,
            ]);
        }
        $query = new HealthFuluOrderItem();
        //查询我的订单
        $orderIds = HealthFuluOrder::where('user_id', $this->auth->id)->where('pay_status', 1)->column('id');
        $paginate = $query
            ->with(['orderInfo'])
            ->field('id,order_id,goods_name,price,status')
            ->whereIn('order_id', $orderIds)
            ->order('id', 'desc')
            ->paginate($this->request->param('limit/d', 10));
        $lists    = [];
        foreach ($paginate->items() as $item) {
            $lists[] = [
                'id'         => $item['id'],
                'goods_name' => $item['goods_name'],
                'price'      => $item['price'],
                'status'     => $item['status'],
                'order_no'   => $item['order_info']['order_no'],
            ];
        }
        $this->success('success', [
            'lists' => $lists,
            'total' => $paginate->total()
        ]);
    }

    /**
     * 激活权益
     * @return void
     * @throws DbException
     * @throws RedisException
     */
    public function activate_item(): void
    {
        $orderItem = HealthFuluOrderItem::get($this->request->param('id'));
        if (!$orderItem) {
            $this->error('未查询到记录');
        }
        $orderInfo = $orderItem->order_info;
        if (empty($orderInfo['order_no'])) {
            $this->error('权益订单异常,请联系客服');
        }
        if ($orderInfo['type'] === 3 && !EquityCenterService::isPajkVip($this->auth->mobile)) {
            $this->error('您还不是会员或会员信息未同步,请稍后再试');
        }
        if ($orderItem['status'] === 1) {
            $this->error('权益已充值');
        }
        if ($orderItem['status'] === 2) {
            $this->error('权益充值失败,请联系客服');
        }
        queue_custom('app\common\job\FuluOrderRechargeJob', ['order_id' => $orderItem['order_id']]);
        $this->success('success');
    }

    /**
     * 查询权益状态
     * @return void
     * @throws DbException
     */
    public function item_status(): void
    {
        $orderItem = HealthFuluOrderItem::get($this->request->param('id'));
        if (!$orderItem) {
            $this->error('未查询到记录');
        }
        $this->success('success', ['status' => $orderItem['status']]);
    }
}